import MySQLdb
from time import sleep
from DBUtils.PooledDB import PooledDB
from warnings import filterwarnings
filterwarnings('ignore',category=MySQLdb.Warning)
from newapp.config import config

class MySQL(object):
    def __init__(self,config):
        self.config = config
        self.conn = self.connect(config)
        
    def connect(self,config):
        pooled = PooledDB(MySQLdb, **config)
        return pooled.connection()
        
    def cursor(self,temp=None):
        tmp = MySQLdb.cursors.DictCursor if not temp else temp 
        cur = self.conn.cursor(cursorclass=tmp)
        return cur
    
    def __fromTupleTranDict(self,cur,tup):
        return [dict(zip([desc[0] for desc in cur.description], row)) for row in tup]
    
    def fetchall(self,sql):
        cur = self.cursor()
        cur.execute(sql)
        return cur.fetchall()
    
    def fetchone(self,sql):
        cur = self.cursor()
        cur.execute(sql)
        return cur.fetchone()
    
    def execute(self, sql):
        cur = self.cursor()
        rs = cur.execute(sql)
        #cur.close()
        return rs

    def insertID(self):
        cur = self.cursor()
        cur.execute("SELECT @@IDENTITY AS id")
        result = cur.fetchall()
        return result[0]['id']
    
    def fetchmany(self, sql, params=None):
        cur = self.cursor()
        cur.execute(sql,params)
        return cur.fetchmany()
    
    def executemany(self, sql, param):
        cur = self.cursor()
        cur.executemany(sql,param)

def dbconn():
    global connargs
    return MySQL(config)

def test():
    db = MySQL(config)
    sql = "SELECT * FROM sem.searchaccount WHERE id=1"
    res = db.fetchone(sql)
    print res
    
if __name__ == '__main__':
    test()